/*
 * @Description:
 * @Author: 孟德永
 * @Date: 2021-02-09 11:58:57
 */

const isWin = process.platform === 'win32';

module.exports = {
    load() {
        // 当 package 被正确加载的时候执行
    },

    unload() {
        // 当 package 被正确卸载的时候执行
    },

    messages: {
        'say-hello': function () {
            Editor.log('Hello World!');
        },
        'scene:saved': function (event) { Editor.log('scene saved!'); },
        parse(event, cbParams) {
            //#region 遍历获取excel文件列表
            Editor.log('reslist start!');
            const fileMap = {};
            // "particle": {
            //   "plist":false
            // },

            for (const key in config) {
                fileMap[key] = {};
                const fullSrcPath = path.join(Editor.Project && Editor.Project.path ? Editor.Project.path : Editor.Project.path, RES_PATH, key) + path.sep;
                // Editor.log(`fullSrcPath = ${fullSrcPath}`);
                readFileList(fullSrcPath, fileMap[key], config[key], false);
            }

            const bundlePath = path.join(Editor.Project && Editor.Project.path ? Editor.Project.path : Editor.Project.path, BUNDLE_PATH);
            const files = fs.readdirSync(bundlePath);
            files.forEach((file, index) => {
                // Editor.log("file = " + file);
                const tmp = file.split('.');
                const type = tmp.pop();
                if (type == 'meta') {
                    const fullPath = path.join(bundlePath, file);
                    const str = fs.readFileSync(fullPath, 'utf8');
                    const data = JSON.parse(str);
                    if (data['bundleName']) {
                        const bundName = data['bundleName'];
                        // Editor.log("bundName:" + bundName);
                        for (const key in config) {
                            const fullSrcPath = path.join(Editor.Project && Editor.Project.path ? Editor.Project.path : Editor.Project.path, BUNDLE_PATH, bundName, key) + path.sep;
                            const isexist = fs.existsSync(fullSrcPath);
                            if (isexist) {
                                // Editor.log('fullSrcPath:' + fullSrcPath);
                                readFileList(fullSrcPath, fileMap[key], config[key], data['bundleName']);
                            }
                        }
                    }
                }
            });

            const fullDstPath = path.join(Editor.Project && Editor.Project.path ? Editor.Project.path : Editor.Project.path, DST_PATH) + path.sep;
            const dest_file = path.resolve(fullDstPath, File_Name);
            const fileJson = JSON.stringify(fileMap, null, 2); //, null, 2
            fs.writeFile(dest_file, fileJson, (err) => {
                if (err) {
                    Editor.error('save json error：', err);
                    throw err;
                }
                console.log('exported successfully  -->  ', path.basename(dest_file));
                // Editor.success("reslist 整合完成");
            });

            Editor.assetdb.refresh(`db://${DST_PATH}/ResourceList.json`, (err, results) => {
                if (err) {
                    Editor.assetdb.error('Failed to reimport asset %s, %s', outName, err.stack);
                    return;
                }
                Editor.assetdb._handleRefreshResults(results);
                Editor.success('reslist 整合完成');
            });
        },
    },
};

const fs = require('fs');
const path = require('path');
const config = require('./config.json');

const RES_PATH = path.join('assets', 'resources');
const BUNDLE_PATH = path.join('assets', 'bundle');

const DST_PATH = 'assets/resources';
const File_Name = 'ResourceList.json';

function readFileList(dirPath, fileMap, condition, bundle) {
    const files = fs.readdirSync(dirPath);
    files.forEach((file, index) => {
        const fullPath = path.join(dirPath, file);
        // Editor.log('fullPath:' + fullPath);
        const stat = fs.statSync(fullPath);
        if (stat.isDirectory()) {
            // Editor.log(`文件夹:${file}`);
            readFileList(fullPath + path.sep, fileMap, condition, bundle);
        } else {
            const hasAuto = hasAutoAtlas(dirPath);
            let autoName = null;
            if (hasAuto) {
                const autoArr = dirPath.split(isWin ? '\\' : '/');
                for (let i = autoArr.length - 1; i >= 0; i--) {
                    const a1 = autoArr[i];
                    if (a1 !== '') {
                        autoName = a1;
                        // Editor.log('hasAuto:', autoName, dirPath, autoName, autoArr);
                        break;
                    }
                }
            }
            const f = file.split('.');
            const extName = f.pop();
            let fileName = f.shift();
            // if (hasAuto) {
            //     Editor.log(`bb:${fileName}:${condition[extName]}`);
            // }
            if (condition[extName]) {
                let filePath = null;
                let bundleName = '';

                /** bundle与非bundle处理 */
                if (bundle) {
                    // Editor.log('bb:' + fileName + ':' + filePath);
                    filePath = fullPath.split(BUNDLE_PATH + path.sep)[1];
                    filePath = filePath.slice(0, -(extName.length + 1));
                    bundleName = filePath.slice(0, bundle.length);
                    filePath = filePath.slice(bundle.length + 1, filePath.length);
                }
                else {
                    filePath = fullPath.split(RES_PATH + path.sep)[1];
                    filePath = filePath.slice(0, -(extName.length + 1));
                }
                /** 生成数据 */
                if (hasAuto) {
                    fileName = `${autoName}/${fileName}`;
                }
                fileMap[fileName] = {
                    // bundle: bundleName.replace('\\', '/'),
                    path: filePath.replace(/\\/g, '/'),
                };
                if (bundleName && bundleName !== '') {
                    fileMap[fileName]['bundle'] = bundleName.replace('\\', '/');
                }
                if (hasAuto) {
                    // fileMap[fileName]['auto'] = autoName;
                    // Editor.log(`文件:${fileName}:${filePath}`);
                }
            }
        }
    });
}

/** 检测是否有自动图集 */
function hasAutoAtlas(dirPath) {
    let has = false;
    const files = fs.readdirSync(dirPath);
    files.forEach((file, index) => {
        const f = file.split('.');
        const extName = f.pop();
        if (extName === 'pac') {
            has = true;
            // Editor.log(`cc:${file}`);
        }
    });
    return has;
}
